package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.CustomLayout;
import com.diudiutechnology.www.yadiudiu.util.utils.ImgUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.PermissionsChecker;
import com.diudiutechnology.www.yadiudiu.util.utils.PictureUtil;
import com.diudiutechnology.www.yadiudiu.util.utils.SelectPhotoPop;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.UserInfoUtils;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyAdapter.MyAdapters;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.ImageManagementModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MineFragmentModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Administrator on 2017/9/13.
 * 图片管理
 */

public class ImageManagementActivity extends Activity implements View.OnClickListener, Callback.CommonCallback<String> {
    @Bind(R.id.retur)
    LinearLayout retur;

    @Bind(R.id.posted_layout)//店铺广告图
            RelativeLayout posted_layout;
    @Bind(R.id.customLayout)
    CustomLayout customLayout;
    @Bind(R.id.ad_pager)
    ViewPager ad_pager;
    @Bind(R.id.ad_layer)
    LinearLayout ad_layer; // 圈圈 布局
    @Bind(R.id.imageView_layout)//添加广告
            RelativeLayout imageView_layout;

    @Bind(R.id.advertising)//列表图片展示
            ImageView advertising;
    @Bind(R.id.advertising_layout)//列表图片
            RelativeLayout advertising_layout;
    @Bind(R.id.store_list_image)//列表图片隐藏
            LinearLayout store_list_image;

    @Bind(R.id.title_right)//保存
            TextView title_right;

    Context context;
    private SelectPhotoPop selectPhotoPop;
    private View viewkre;
    private MyProgressDialog mDialog;
    String Judge_number = "0";//判断哪个图片   0、店铺广告图 1、店铺列表图 2 、店铺广告图展示  3、店铺列表图 展示
    String Judge_interface = "0";//判断哪个接口   0、获取店铺资料 1、上传图片 2、上传店铺资料 3、删除图片
    String adverti = "";//列表图片
    String posted = "";//循环广告
    String u_id = "";
    int pos = 0;//删除id
    private DisplayImageOptions options;
    private ImageLoader imageLoader;
    List<String> pics = new ArrayList<>();//图片数组
    List<String> addpics = new ArrayList<>();//图片数组
    MyAdapters adapter;
    String merchanttype = "";//类型

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewkre = View.inflate(this, R.layout.activity_image_management, null);
        setContentView(viewkre);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        posted_layout.setOnClickListener(this);
        advertising_layout.setOnClickListener(this);
        imageView_layout.setOnClickListener(this);
        advertising.setOnClickListener(this);
        title_right.setOnClickListener(this);
        if (getIntent() != null) {
            u_id = getIntent().getStringExtra("id");
        }
        options = ImgUtils.imageOptions();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        adapter = new MyAdapters(context, pics,0);
        ad_pager.setAdapter(adapter);
        initData();
        markepic();
    }

    //绑定逻辑
    private void initData() {
        MineFragmentModel mineFragmentModel = UserInfoUtils.readUserInfo(this);
        merchanttype = mineFragmentModel.getMerchanttype();
        if (merchanttype.equals("1")) {//房产商家
            //列表图片隐藏
            store_list_image.setVisibility(View.GONE);
        } else if (merchanttype.equals("2")) {//购车商家
            //列表图片隐藏
            store_list_image.setVisibility(View.GONE);
        } else if (merchanttype.equals("3")) {//干洗商家

        } else if (merchanttype.equals("4")) {//开锁商家

        } else if (merchanttype.equals("5")) {//果蔬商家

        } else if (merchanttype.equals("6")) {//苦力商家

        } else if (merchanttype.equals("7")) {//快递商家

        } else if (merchanttype.equals("8")) {//家政商家

        } else if (merchanttype.equals("9")) {//洗车商家

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
            case R.id.posted_layout://店铺广告图
                processadd("0");
                break;
            case R.id.advertising_layout://列表图片
                processadd("1");
                break;
            case R.id.imageView_layout://添加广告
                if (addpics.size() < 6) {
                    processadd("2");
                } else {
                    ToastUtils.show(context, getResources().getString(R.string.add_six_images));
                }
                break;
            case R.id.advertising://列表图片展示
                processadd("3");
                break;
            /* 注释  相机*/
            case R.id.item_popupwindows_camera:
                selectPhotoPop.dismiss();
                GalleryFinal.openCamera(Constant.CAMERA, MyApplication.getInstance().initGalley(Constant.CAMERA, 1), mOnHanlderResultCallback);
                break;
            /* 注释  相册*/
            case R.id.item_popupwindows_Photo:
                selectPhotoPop.dismiss();
                GalleryFinal.openGallerySingle(Constant.GALLERYSINGLE, MyApplication.getInstance().initGalley(Constant.GALLERYSINGLE, 1), mOnHanlderResultCallback);
                break;
            /* 注释  取消*/
            case R.id.item_popupwindows_cancel:
                selectPhotoPop.dismiss();
                break;
            case R.id.title_right://保存
                if (addpics.size() > 0) {
                    for (int i = 0; i < addpics.size(); i++) {
                        if (posted.equals("")) {
                            posted = addpics.get(i);
                        } else {
                            posted = posted + "|" + addpics.get(i);
                        }
                    }
                }
                if (TextUtils.isEmpty(posted)) {//广告
                    ToastUtils.show(context, getResources().getString(R.string.please_add_image));
                    return;
                }
                processData();
                break;
        }
    }

    //上传数据
    private void processData() {

        if (merchanttype.equals("1") || merchanttype.equals("2")) {//房产商家和购车商家

        } else {
            if (TextUtils.isEmpty(adverti)) {//列表
                ToastUtils.show(context, getResources().getString(R.string.please_addlist_image));
                return;
            }
        }
        processmanagement();

    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), Constant.WIDE, Constant.WIDE);
            String conimg = PictureUtil.saveBitmapFile(bitmap, String.valueOf(0));
            processupload(conimg);
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    //轮播广告
    public void getadvertising(final int size) {
        adapter.addImet(pics);
        ad_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                Sundry.refreshPoint(ad_layer, position % size, 0);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        Sundry.initPointsLayout(ad_layer, context, size, 0);
    }

    //删除轮播图
    public void processdeleting(int pos, String pic) {
        this.pos = pos;
        delfile(pic);
    }

    //调用相机
    private void processadd(String pos) {
        if (!PermissionsChecker.getPermissionsChecker(this, "0", 0)) {
            if (!PermissionsChecker.getPermissionsChecker(this, "0", 2)) {
                Judge_number = pos;
                showSelectPicPop();
            } else {
                ToastUtils.show(context, "请检查是否打开储存权限");
            }
        } else {
            ToastUtils.show(context, "请检查是否打开相机权限");
        }
    }

    //相册
    private void showSelectPicPop() {
        selectPhotoPop = new SelectPhotoPop(this, this);
        selectPhotoPop.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
    }

    //图片管理
    private void markepic() {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "0";
            mDialog = new MyProgressDialog(context);
            HttpClient.markepic(u_id, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //上传图片
    private void processupload(String upload) {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "1";
            mDialog = new MyProgressDialog(context);
            HttpClient.upload(upload, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //上传店铺图片管理
    private void processmanagement() {
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "2";
            mDialog = new MyProgressDialog(context);
            HttpClient.management(posted, adverti, u_id, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //删除图片
    private void delfile(String upload) {
        String posteds="";
        if (addpics.size() > 0) {
            for (int i = 0; i < addpics.size(); i++) {
                if (posteds.equals("")) {
                    if (!upload.equals(addpics.get(i))){
                        posteds = addpics.get(i);
                    }

                } else {
                    if (!upload.equals(addpics.get(i))){
                        posteds = posteds + "|" + addpics.get(i);
                    }
                }
            }
        }
        if (Sundry.isOpenNetwork(context)) {
            Judge_interface = "3";
            mDialog = new MyProgressDialog(context);
            HttpClient.delimages(upload,u_id,posteds, this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote != null || getnote.size() > 0) {
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")) {
                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")) {//类型
                    List<ImageManagementModel> getmarkepic = JsonTools.getmarkepic(content);
                    if (getmarkepic != null || getmarkepic.size() > 0) {
                        adverti = getmarkepic.get(0).getListpic();
                        if (!TextUtils.isEmpty(adverti)) {
                            imageLoader.displayImage(Constant.HTTP + adverti, advertising, options);
                            advertising_layout.setVisibility(View.GONE);
                            advertising.setVisibility(View.VISIBLE);
                        } else {
                            advertising_layout.setVisibility(View.VISIBLE);
                            advertising.setVisibility(View.GONE);
                        }
                        String figurepic = getmarkepic.get(0).getFigurepic();
                        if (!TextUtils.isEmpty(figurepic)) {
                            posted_layout.setVisibility(View.GONE);
                            customLayout.setVisibility(View.VISIBLE);
                            imageView_layout.setVisibility(View.VISIBLE);
                            String[] split = figurepic.split("\\|");
                            System.out.println("stringmd5result" + split.length);
                            for (int i = 0; i < split.length; i++) {
                                if (!TextUtils.isEmpty(split[i])) {
                                    pics.add(split[i]);
                                }
                            }
                            addpics = pics;
                            getadvertising(pics.size());
                        } else {
                            posted_layout.setVisibility(View.VISIBLE);
                            customLayout.setVisibility(View.GONE);
                            imageView_layout.setVisibility(View.GONE);
                        }
                    }
                } else if (Judge_interface.equals("1")) {//图片
                    if (Judge_number.equals("0")) {//店铺广告图
                        if (!TextUtils.isEmpty(content)) {
                            posted_layout.setVisibility(View.GONE);
                            customLayout.setVisibility(View.VISIBLE);
                            imageView_layout.setVisibility(View.VISIBLE);
                            pics.add(content);
                            addpics = pics;
                            getadvertising(pics.size());
                        }
                    } else if (Judge_number.equals("1")) {//店铺列表图
                        if (!TextUtils.isEmpty(content)) {
                            adverti = content;
                            imageLoader.displayImage(Constant.HTTP + content, advertising, options);
                            advertising_layout.setVisibility(View.GONE);
                            advertising.setVisibility(View.VISIBLE);
                        } else {
                            advertising_layout.setVisibility(View.VISIBLE);
                            advertising.setVisibility(View.GONE);
                        }
                    } else if (Judge_number.equals("2")) {//店铺广告图
                        pics.add(pics.size(), content);
                        addpics = pics;
                        getadvertising(pics.size());
                    } else if (Judge_number.equals("3")) {//店铺列表图
                        adverti = content;
                        imageLoader.displayImage(Constant.HTTP + content, advertising, options);
                    }
                } else if (Judge_interface.equals("2")) {// 申请
                    finish();
                    ToastUtils.show(context, mssage);
                }else if (Judge_interface.equals("3")) {// 删除图片
                    pics.remove(pos);
                    addpics = pics;
                    if (pics.size() > 0) {
                        getadvertising(pics.size());
                    } else {
                        posted_layout.setVisibility(View.VISIBLE);
                        customLayout.setVisibility(View.GONE);
                        imageView_layout.setVisibility(View.GONE);
                    }
                }
            } else if (error.equals("105")) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            } else {
                ToastUtils.show(context, mssage);
            }
        }
    }


    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(Callback.CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
}

